import http from '../request.js'
import { API_ENDPOINTS } from '../config.js'

/**
 * 订单相关API模块
 * 包含订单创建、列表、详情、更新、支付等功能
 */
class OrderAPI {
  /**
   * 创建订单
   * @param {Object} data 订单数据
   * @param {String} data.deviceId 设备ID
   * @param {String} data.startDate 租赁开始日期
   * @param {String} data.endDate 租赁结束日期
   * @param {Number} data.quantity 租赁数量
   * @param {String} data.deliveryAddress 交付地址
   * @param {String} data.remarks 备注
   * @param {Object} data.requirements 详细需求参数
   */
  async createOrder(data) {
    try {
      const result = await http.post(API_ENDPOINTS.ORDERS.CREATE, data)
      return result
    } catch (error) {
      console.error('创建订单失败:', error)
      throw error
    }
  }

  /**
   * 获取订单列表
   * @param {Object} params 查询参数
   * @param {Number} params.page 页码
   * @param {Number} params.pageSize 每页数量
   * @param {String} params.status 订单状态筛选
   * @param {String} params.type 订单类型筛选：rent/owner
   */
  async getOrderList(params = {}, retryCount = 0) {
    try {
      const result = await http.get(API_ENDPOINTS.ORDERS.LIST, params)
      
      // 检查是否需要重试（token刷新后）
      if (result.needRetry && retryCount < 1) {
        console.log('🔄 Token已刷新，重新获取订单列表...')
        return await this.getOrderList(params, retryCount + 1)
      }
      
      return result
    } catch (error) {
      console.error('获取订单列表失败:', error)
      throw error
    }
  }

  /**
   * 获取我的订单（租赁方）
   * @param {Object} params 查询参数
   */
  async getMyOrders(params = {}) {
    try {
      const result = await http.get(API_ENDPOINTS.ORDERS.MY_ORDERS, params)
      return result
    } catch (error) {
      console.error('获取我的订单失败:', error)
      throw error
    }
  }

  /**
   * 获取订单详情
   * @param {String} orderId 订单ID
   */
  async getOrderDetail(orderId) {
    try {
      const result = await http.get(`${API_ENDPOINTS.ORDERS.DETAIL}/${orderId}`)
      return result
    } catch (error) {
      console.error('获取订单详情失败:', error)
      throw error
    }
  }

  /**
   * 更新订单
   * @param {String} orderId 订单ID
   * @param {Object} data 更新数据
   */
  async updateOrder(orderId, data) {
    try {
      const result = await http.put(`${API_ENDPOINTS.ORDERS.UPDATE}/${orderId}`, data)
      return result
    } catch (error) {
      console.error('更新订单失败:', error)
      throw error
    }
  }

  /**
   * 更新订单状态
   * @param {String} orderId 订单ID
   * @param {String} status 新状态
   * @param {String} remark 备注（可选）
   */
  async updateOrderStatus(orderId, status, remark = '') {
    try {
      const result = await http.put(`/orders/${orderId}/status`, {
        status,
        remark
      })
      return result
    } catch (error) {
      console.error('更新订单状态失败:', error)
      throw error
    }
  }

  /**
   * 取消订单
   * @param {String} orderId 订单ID
   * @param {String} reason 取消原因
   */
  async cancelOrder(orderId, reason) {
    try {
      const result = await http.put(`/orders/${orderId}/cancel`, {
        reason
      })
      return result
    } catch (error) {
      console.error('取消订单失败:', error)
      throw error
    }
  }

  /**
   * 确认订单（出租方确认）
   * @param {String} orderId 订单ID
   * @param {Object} data 确认数据
   * @param {String} data.ownerRemark 出租方备注
   */
  async confirmOrder(orderId, data = {}) {
    try {
      const result = await http.put(`/orders/${orderId}/confirm`, data)
      return result
    } catch (error) {
      console.error('确认订单失败:', error)
      throw error
    }
  }

  /**
   * 拒绝订单（出租方拒绝）
   * @param {String} orderId 订单ID
   * @param {String} reason 拒绝原因
   */
  async rejectOrder(orderId, reason) {
    try {
      const result = await http.put(`/orders/${orderId}/reject`, {
        reason
      })
      return result
    } catch (error) {
      console.error('拒绝订单失败:', error)
      throw error
    }
  }

  /**
   * 订单完成确认（设备归还）
   * @param {String} orderId 订单ID
   * @param {Object} data 完成数据
   */
  async completeOrder(orderId, data = {}) {
    try {
      const result = await http.put(`/orders/${orderId}/complete`, data)
      return result
    } catch (error) {
      console.error('完成订单失败:', error)
      throw error
    }
  }

  /**
   * 上传订单需求文件
   * @param {String} orderId 订单ID
   * @param {String} filePath 文件路径
   * @param {Object} formData 额外表单数据
   */
  async uploadRequirements(orderId, filePath, formData = {}) {
    try {
      const result = await http.upload(
        `${API_ENDPOINTS.ORDERS.UPLOAD_REQUIREMENTS}/${orderId}`,
        filePath,
        formData,
        { name: 'requirements' }
      )
      return result
    } catch (error) {
      console.error('上传需求文件失败:', error)
      throw error
    }
  }

  /**
   * 删除订单需求文件
   * @param {String} orderId 订单ID
   * @param {String} fileName 文件名
   */
  async deleteRequirements(orderId, fileName) {
    try {
      const result = await http.delete(`/orders/${orderId}/requirements/${fileName}`)
      return result
    } catch (error) {
      console.error('删除需求文件失败:', error)
      throw error
    }
  }

  /**
   * 获取订单支付信息
   * @param {String} orderId 订单ID
   */
  async getPaymentInfo(orderId) {
    try {
      const result = await http.get(`/orders/${orderId}/payment`)
      return result
    } catch (error) {
      console.error('获取支付信息失败:', error)
      throw error
    }
  }

  /**
   * 创建支付
   * @param {String} orderId 订单ID
   * @param {Object} data 支付数据
   * @param {String} data.type 支付类型：DEPOSIT/RENT
   * @param {String} data.method 支付方式：WECHAT/ALIPAY/BANK_TRANSFER
   * @param {Number} data.amount 支付金额
   */
  async createPayment(orderId, data) {
    try {
      const result = await http.post(`/orders/${orderId}/payment`, data)
      return result
    } catch (error) {
      console.error('创建支付失败:', error)
      throw error
    }
  }

  /**
   * 上传支付凭证（银行转账）
   * @param {String} paymentId 支付ID
   * @param {String} filePath 支付凭证图片路径
   */
  async uploadPaymentProof(paymentId, filePath) {
    try {
      const result = await http.upload(
        `/payments/${paymentId}/proof`,
        filePath,
        {},
        { name: 'screenshot' }
      )
      return result
    } catch (error) {
      console.error('上传支付凭证失败:', error)
      throw error
    }
  }

  /**
   * 验证支付（管理员）
   * @param {String} paymentId 支付ID
   * @param {Boolean} approved 是否通过
   * @param {String} remark 审核备注
   */
  async verifyPayment(paymentId, approved, remark = '') {
    try {
      const result = await http.put(`/payments/${paymentId}/verify`, {
        approved,
        remark
      })
      return result
    } catch (error) {
      console.error('验证支付失败:', error)
      throw error
    }
  }

  /**
   * 申请退款
   * @param {String} orderId 订单ID
   * @param {Object} data 退款数据
   * @param {String} data.reason 退款原因
   * @param {Number} data.amount 退款金额
   */
  async requestRefund(orderId, data) {
    try {
      const result = await http.post(`/orders/${orderId}/refund`, data)
      return result
    } catch (error) {
      console.error('申请退款失败:', error)
      throw error
    }
  }

  /**
   * 处理退款（管理员）
   * @param {String} refundId 退款ID
   * @param {Boolean} approved 是否批准
   * @param {String} remark 处理备注
   */
  async processRefund(refundId, approved, remark = '') {
    try {
      const result = await http.put(`/refunds/${refundId}/process`, {
        approved,
        remark
      })
      return result
    } catch (error) {
      console.error('处理退款失败:', error)
      throw error
    }
  }

  /**
   * 获取订单统计信息
   * @param {Object} params 查询参数
   */
  async getOrderStats(params = {}) {
    try {
      const result = await http.get('/orders/stats', params)
      return result
    } catch (error) {
      console.error('获取订单统计失败:', error)
      throw error
    }
  }

  /**
   * 计算订单费用
   * @param {String} deviceId 设备ID
   * @param {String} startDate 开始日期
   * @param {String} endDate 结束日期
   * @param {Number} quantity 数量
   */
  async calculateOrderCost(deviceId, startDate, endDate, quantity = 1) {
    try {
      const result = await http.post('/orders/calculate-cost', {
        deviceId,
        startDate,
        endDate,
        quantity
      })
      return result
    } catch (error) {
      console.error('计算订单费用失败:', error)
      throw error
    }
  }

  /**
   * 获取订单时间线
   * @param {String} orderId 订单ID
   */
  async getOrderTimeline(orderId) {
    try {
      const result = await http.get(`/orders/${orderId}/timeline`)
      return result
    } catch (error) {
      console.error('获取订单时间线失败:', error)
      throw error
    }
  }

  /**
   * 订单评价
   * @param {String} orderId 订单ID
   * @param {Object} data 评价数据
   * @param {Number} data.rating 评分 1-5
   * @param {String} data.comment 评价内容
   * @param {Array} data.images 评价图片（可选）
   */
  async reviewOrder(orderId, data) {
    try {
      const result = await http.post(`/orders/${orderId}/review`, data)
      return result
    } catch (error) {
      console.error('订单评价失败:', error)
      throw error
    }
  }

  /**
   * 获取订单评价
   * @param {String} orderId 订单ID
   */
  async getOrderReview(orderId) {
    try {
      const result = await http.get(`/orders/${orderId}/review`)
      return result
    } catch (error) {
      console.error('获取订单评价失败:', error)
      throw error
    }
  }

  /**
   * 订单投诉
   * @param {String} orderId 订单ID
   * @param {Object} data 投诉数据
   * @param {String} data.reason 投诉原因
   * @param {String} data.description 详细描述
   * @param {Array} data.evidence 证据图片（可选）
   */
  async complainOrder(orderId, data) {
    try {
      const result = await http.post(`/orders/${orderId}/complaint`, data)
      return result
    } catch (error) {
      console.error('订单投诉失败:', error)
      throw error
    }
  }

  /**
   * 获取投诉列表（管理员）
   * @param {Object} params 查询参数
   */
  async getComplaints(params = {}) {
    try {
      const result = await http.get('/complaints', params)
      return result
    } catch (error) {
      console.error('获取投诉列表失败:', error)
      throw error
    }
  }

  /**
   * 处理投诉（管理员）
   * @param {String} complaintId 投诉ID
   * @param {Object} data 处理数据
   */
  async processComplaint(complaintId, data) {
    try {
      const result = await http.put(`/complaints/${complaintId}/process`, data)
      return result
    } catch (error) {
      console.error('处理投诉失败:', error)
      throw error
    }
  }

  /**
   * 批量操作订单（管理员）
   * @param {Array} orderIds 订单ID数组
   * @param {String} action 操作类型
   * @param {Object} params 操作参数
   */
  async batchOperation(orderIds, action, params = {}) {
    try {
      const result = await http.post('/orders/batch-operation', {
        orderIds,
        action,
        params
      })
      return result
    } catch (error) {
      console.error('批量操作订单失败:', error)
      throw error
    }
  }

  /**
   * 导出订单数据（管理员）
   * @param {Object} params 导出参数
   */
  async exportOrders(params = {}) {
    try {
      const result = await http.get('/orders/export', params)
      return result
    } catch (error) {
      console.error('导出订单数据失败:', error)
      throw error
    }
  }

  /**
   * 获取订单管理统计（管理员）
   * @param {Object} params 查询参数
   */
  async getManagementStats(params = {}) {
    try {
      const result = await http.get('/orders/management-stats', params)
      return result
    } catch (error) {
      console.error('获取管理统计失败:', error)
      throw error
    }
  }

  /**
   * 生成订单合同
   * @param {String} orderId 订单ID
   */
  async generateContract(orderId) {
    try {
      const result = await http.post(`/orders/${orderId}/contract`)
      return result
    } catch (error) {
      console.error('生成合同失败:', error)
      throw error
    }
  }

  /**
   * 下载订单合同
   * @param {String} orderId 订单ID
   */
  async downloadContract(orderId) {
    try {
      const result = await http.get(`/orders/${orderId}/contract/download`)
      return result
    } catch (error) {
      console.error('下载合同失败:', error)
      throw error
    }
  }
}

// 创建实例并导出
const orderAPI = new OrderAPI()
export default orderAPI 